﻿using M_Manufacture.API.Application.Command.WorkOrderCommand;
using M_Manufacture.Domain;
using M_Manufacture.Domain.DTO;
using M_Manufacture.Repository.Interface;
using MediatR;

namespace M_Manufacture.API.Application.CommandHandlers.WorkOrderCommandHandler
{
    /// <summary>
    /// 显示工单
    /// </summary>
    public class ShowWorkOrderCommandHabndler : IRequestHandler<ShowWorkOrderCommand, PageDto<WorkOrder>>
    {
        private readonly IWorkOrderRepository _workOrderRepository;
        public ShowWorkOrderCommandHabndler(IWorkOrderRepository workOrderRepository)
        {
            _workOrderRepository = workOrderRepository;
        }
        public async Task<PageDto<WorkOrder>> Handle(ShowWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var workList = await _workOrderRepository.GetAsync(d => !d.IsDeleted);
            if (!string.IsNullOrEmpty(request.WorkOrderCode))
            {
                workList= workList.Where(d=>d.WorkOrderCode.Contains(request.WorkOrderCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.WorkOrderSart))
            {
                workList = workList.Where(d => d.WorkOrderSart==request.WorkOrderSart).ToList();
            }
            if (!string.IsNullOrEmpty(request.CreatedDate))
            {
                workList = workList.Where(d => d.CreatedDate ==Convert.ToDateTime(request.CreatedDate)).ToList();
            }
            if (request.PageSize == null)
            {
                request.PageSize = workList.Count();
            }
            if (request.PageIndex == null)
            {
                request.PageSize =1;
            }
            PageDto<WorkOrder> page= new PageDto<WorkOrder>();
            page.TotalCount = workList.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = workList.OrderByDescending(d=>d.CreatedDate).Skip((int)(request.PageIndex-1)*(int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;

        }
    }
}
